package com.android.sunnyweather.ui.place

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.android.sunnyweather.logic.Repository
import com.android.sunnyweather.logic.model.Place

class PlaceViewModel : ViewModel(){

    fun savePlace(place: Place) = Repository.savePlace(place)
    fun getSavePlace() = Repository.getSavedPlace()
    fun isPlaceSaved() = Repository.isPlaceSaved()

    private val searchLiveData = MutableLiveData<String>()

    //对界面上显示的城市数据进行缓存，原则上界面相关的数据都应该放到ViewModel中，防止屏幕旋转导致数据消失
    val placeList = ArrayList<Place>()

    //将传入的搜索参数query赋值给searchLiveData对象，并使用Transformations.switchMap进行观察
    val plaLiveData = Transformations.switchMap(searchLiveData){query ->
        Repository.searchPlaces(query)
    }

    fun searchPlaces(query: String){
        searchLiveData.value = query
    }
}